package com.car.serve.config;

import org.apache.ibatis.session.Configuration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

import java.util.List;


@org.springframework.context.annotation.Configuration
@EnableConfigurationProperties(TypeHandlerProperties.class)
public class MyBatisConfig {
    private final TypeHandlerProperties typeHandlerProperties;

    public MyBatisConfig(TypeHandlerProperties typeHandlerProperties) {
        this.typeHandlerProperties = typeHandlerProperties;
    }

    @Bean
    public Configuration mybatisConfiguration(){
        Configuration configuration = new Configuration();

        // 获取TypeHandler的配置信息
        String packagePath = typeHandlerProperties.getPackagePath();
        List<TypeHandlerProperties.TypeHandlerConfig> configs = typeHandlerProperties.getConfigs();

        // 注册自定义TypeHandler
        if (packagePath != null && !packagePath.isEmpty()) {
            configuration.getTypeHandlerRegistry().register(packagePath);
        }

        // 根据配置信息逐个注册自定义TypeHandler
        if (configs != null) {
            for (TypeHandlerProperties.TypeHandlerConfig config : configs) {
                String handler = config.getHandler();
                String javaType = config.getJavaType();
                try {
                    configuration.getTypeHandlerRegistry().register(Class.forName(javaType), Class.forName(handler));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }

            }
        }

        return configuration;
    }
}
